package com.cmq.web_1.api_test;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import java.lang.reflect.Type;

public class JsonUtil {
    private static final Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd HH:mm:ss")
            .setPrettyPrinting()
            .create();

    // 对象转JSON字符串
    public static String toJson(Object obj) {
        return gson.toJson(obj);
    }

    // JSON字符串转对象
    public static <T> T fromJson(String json, Class<T> classOfT) {
        try {
            return gson.fromJson(json, classOfT);
        } catch (JsonSyntaxException e) {
            throw new RuntimeException("JSON解析错误: " + e.getMessage(), e);
        }
    }

    // JSON字符串转对象（支持泛型）
    public static <T> T fromJson(String json, Type typeOfT) {
        try {
            return gson.fromJson(json, typeOfT);
        } catch (JsonSyntaxException e) {
            throw new RuntimeException("JSON解析错误: " + e.getMessage(), e);
        }
    }
}